import React, { useState } from 'react'
import { nanoid } from 'nanoid';

export default function App() {
    const [text, setText] = useState("");
    const [list, setList] = useState([
        {
            id: nanoid(),
            name: "张三",
            isChecked: false,
        }
    ])
    const [defaultChecked, setDefaultChecked] = useState(false)

    const handlerInput = (evt) => {
        setText(evt.target.value)
    }
    const handlerAdd = () => {
        setList([...list, {
            id: nanoid(),
            name: text,
            isChecked: defaultChecked,
        }])
        setText("")
    }
    const handlerDelete = (index) => {
        var newList = [...list];
        newList.splice(index, 1)
        setList(newList)
    }
    const handlerChecked = (index) => {
        var newList = [...list];
        newList[index].isChecked = !newList[index].isChecked
        setList(newList)
        console.log(list);
    }

    const handlerIfFinish = (evt) => {
        setDefaultChecked(evt.target.checked)
    }
    return (
        <div>
            <input onChange={handlerInput} value={text} />
            <button onClick={handlerAdd}>Add</button>
            <input type="checkbox" onChange={handlerIfFinish}/>是否完成
            <ul>
                {
                    list.map((item, index) =>
                        <li key={item.id}>
                            <input type="checkbox" checked={item.isChecked} onChange={() => { 
                                handlerChecked(index)
                            }}/>
                            <span style={{ textDecoration: item.isChecked ? "line-through" : "" }}>{item.name}</span>
                            <button onClick={() => {
                                handlerDelete(index)
                            }}>delete</button>
                        </li>
                    )
                }
            </ul>
            {list.length === 0 && <div>暂无数据</div>}
        </div>
    )
}
